<?php

namespace app\admin\logic;

use app\admin\model\MenuNode;
use app\admin\model\RoleNode;


/**
 * menu noe
 * Class MenuNodeLogic
 * @package app\admin\logic
 * @author ^2_3^王尔贝
 */
class MenuNodeLogic
{
    private $menuNodeModel;

    private $roleNodeModel;

    public function __construct()
    {
        $this->menuNodeModel = new MenuNode();
        $this->roleNodeModel = new RoleNode();
    }

    /**
     * 管理员菜单
     * @param array $params
     * @return array
     * @author ^2_3^王尔贝
     */
    public function adminNav($params = [])
    {
        $navArr = [];
        if( empty( $params ) || empty( $params['role_ids'] ) ) {
            return $navArr;
        }

        $where = [];
        if( !in_array(1, $params['role_ids']) ) {
            //// role node
            $roleIds = $params['role_ids'];
            $rnWhere = [
                ['role_id', 'in', $roleIds]
            ];
            $nodeIds = $this->roleNodeModel->_column($rnWhere, 'node_id');
            $nodeIds && $nodeIds = array_unique( $nodeIds );

            $nodeIds && $where[] = ['id', 'in', $nodeIds];
        }
        $where[] = ['is_menu', '=', 1];


        $field = "
            id,
            title,
            name,
            pid as parentId,
            app,
            controller,
            action,
            icon,
            param,
            status as `show`
        ";
        $nodeList = $this->menuNodeModel->listOnly($where, $field, 'id asc');

        foreach ($nodeList as $key=>$item) {
            $item = $item->toArray();
            $extendArr = [];
            if( !empty( $item['param'] ) ) {
                $extendArr = json_decode( $item['param'], true );
                $item = array_merge((array)$item, $extendArr);
//                unset( $item['param'] );
            }

            $meta = [
                'icon' => $item['icon'],
                'title' => $item['title'],
                'show' => $item['show'],
            ];
            $meta = array_merge($meta, $extendArr);

            $tmp = [
                'name' => $item['name'],
                'parentId' => $item['parentId'],
                'id' => $item['id'],
                'meta' => $meta,
            ];

            $tmp = array_merge($tmp, $extendArr);
            $navArr[] = $tmp;
        }

        return $navArr;
    }

    /**
     * 树形菜单
     * @param array $params
     * @return array
     * @author ^2_3^王尔贝
     */
    public function navTree($params = [])
    {
        $treeArr = [];

        //// list
        $where[] = ['is_menu', '=', 1];
        $list = $this->menuNodeModel->listOnly($where);

        $treeArr = $this->generateTree($list);
        return $treeArr;
    }

    /**
     * 组装树形结构
     * @param array $list
     * @param int $pid
     * @return array
     * @author ^2_3^王尔贝
     */
    private function generateTree($list = [], $pid = 0)
    {
        $result = [];
        if( empty( $list ) ) {
            return $result;
        }

        foreach ( $list as $key=>$item ) {
            $item = $item->toArray();
            if( $item['pid'] == $pid ) {
                $item['key'] = $item['id'];
                $item['value'] = $item['id'];

                //// 扩展数据
                if( !empty( $item['param'] ) ) {
                    $extendArr = json_decode( $item['param'],true);
                    unset( $item['param'] );

                    $item = array_merge($item, $extendArr);
                }

                $childResult = $this->generateTree($list, $item['id']);
                if( !empty( $childResult ) ) {
                    $item['children'] = $childResult;
                }

                $result[] = $item;
            }
        }

        return $result;
    }

    /**
     * 菜单分页列表
     * @param array $params
     * @return array|\think\Paginator
     * @author ^2_3^王尔贝
     */
    public function menuListPage($params = [])
    {
        $where = [];
        $whereOr = [];
        $field = '*';
        $page = $params['page_no'] ?? 1;
        $pageSize = $params['page_size'] ?? 1;

        if( !empty( $params['id'] ) ) {
            $info = $this->menuNodeModel->_find(['id' => $params['id']]);
            if( !empty( $info ) ) {
                $where['id'] = $info['id'];
            }
            //
            $whereOrTmp1 = [
                ['id', '=', $info['pid']]
            ];
            $whereOr[] = $whereOrTmp1;
            //
            $whereOrTmp2 = [
                ['pid', '=', $info['id']]
            ];
            $whereOr[] = $whereOrTmp2;
        }

        $listPage = $this->menuNodeModel->listPage($where, $field, $page, 'id asc', $pageSize, $whereOr);
        foreach ( $listPage->items() as $key=>$item ) {
            $item['key'] = $item['id'];
            if( !empty( $item['param'] ) ) {
                $extendObj = json_decode( $item['param'] );
                foreach ( $extendObj as $objName=>$objValue ) {
                    $item[$objName] = $objValue;
                }
            }

            if( !empty($item['hideHeader']) ) {
                $item['hideHeader'] = 1;
            }else {
                $item['hideHeader'] = 0;
            }
            if( !empty($item['hideChildren']) ) {
                $item['hideChildren'] = 1;
            }else {
                $item['hideChildren'] = 0;
            }
        }
//        $listPage = $listPage->toArray();
//        $listPage['pageSize'] = $listPage['per_page'];
//        $listPage['pageNo'] = $listPage['current_page'];
//        $listPage['totalCount'] = $listPage['total'];
//        $listPage['totalPage'] = ceil( $listPage['totalCount'] / $listPage['pageSize'] );
        return $listPage;
    }

    /**
     * menu node add
     * @param array $params
     * @return bool|\think\Model|static
     * @author ^2_3^王尔贝
     */
    public function save($params = [])
    {
        $flag = false;
        if (empty( $params )) {
            return $flag;
        }

        $data = [];
        if( !empty( $params['id'] ) ) {
            $data['id'] = $params['id'];
        }
        $data['title'] = $params['title'] ?? '';
        $data['name'] = $params['name'] ?? '';
        $data['pid'] = $params['pid'] ?? 0;
        $data['status'] = $params['status'] ?? 0;
        $data['is_menu'] = $params['is_menu'] ?? 1;
        $data['app'] = 'admin';
        $data['controller'] = $params['controller'] ?? '';
        $data['action'] = $params['action'] ?? '';
        $data['icon'] = $params['icon'] ?? '';
        // 额外参数
        $data['param'] = [];
        if( isset($params['component']) ) {
            $data['param']['component'] = $params['component'];
        }
        if( isset($params['redirect']) ) {
            $data['param']['redirect'] = $params['redirect'];
        }
        if( isset($params['path']) ) {
            $data['param']['path'] = $params['path'];
        }
        if( isset($params['group']) ) {
            $data['param']['group'] = $params['group'];
        }
        if( !empty($params['is_hide_header']) ) {
            $data['param']['hideHeader'] = $params['is_hide_header'];
        }
        if( !empty($params['is_hide_children']) ) {
            $data['param']['hideChildren'] = $params['is_hide_children'];
        }
        $data['param'] = json_encode( $data['param'] );

        $flag = $this->menuNodeModel->_saveAll( [$data] );
        return $flag;
    }
}